package cn.zebra.dev.member.module.address.service.impl;

import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.ibatis.plus.utils.Query;
import cn.zebra.dev.member.module.address.dao.MemberAddressDao;
import cn.zebra.dev.member.module.address.entity.MemberAddressEntity;
import cn.zebra.dev.member.module.address.service.MemberAddressService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MemberAddressServiceImpl extends ServiceImpl<MemberAddressDao, MemberAddressEntity> implements MemberAddressService {

    @Override
    public PageUtils<MemberAddressEntity> queryPage(Map<String, Object> params) {
        QueryWrapper<MemberAddressEntity> wrapper = new QueryWrapper<>();
        wrapper.apply(params.containsKey("memberId"), "member_id = {0}", params.get("memberId"));
        wrapper.apply("delete_flag = FALSE");
        IPage<MemberAddressEntity> iPage = this.page(
                new Query<MemberAddressEntity>(params).getPage(),
                wrapper
        );
        return new PageUtils<>(iPage);
    }

    @Override
    public Boolean isEmptyMemberAddress(Long memberId) {
        List<MemberAddressEntity> list = selectList("member_id = {0}", memberId);
        return list == null || list.size() == 0;
    }

    @Override
    public void cancelAllDefault(Long memberId) {
        MemberAddressEntity memberAddress = new MemberAddressEntity();
        memberAddress.setDefaultFlag(false);
        this.update(memberAddress, "member_id = {0}", memberId);
    }

    @Override
    public MemberAddressEntity findById(Long id) {
        QueryWrapper<MemberAddressEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id, recipient_name, phone, province, city, area, address_info, default_flag");
        wrapper.apply("id = {0}", id);
        return this.getOne(wrapper);
    }

    @Override
    public MemberAddressEntity findByIdAndMemberId(Long id, Long memberId) {
        QueryWrapper<MemberAddressEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id, recipient_name, phone, province, city, area, address_info, default_flag");
        wrapper.apply("id = {0} AND member_id = {1}", id, memberId);
        return this.getOne(wrapper);
    }

    /**
     * 根据用户id查找用户默认地址详情
     *
     * @param memberId 用户id
     * @return 用户默认地址详情
     */
    @Override
    public MemberAddressEntity findDefaultAddressByMemberId(Long memberId) {
        QueryWrapper<MemberAddressEntity> wrapper = new QueryWrapper<>();
        wrapper.apply("member_id = {0}", memberId);
        wrapper.apply("default_flag = TRUE");
        wrapper.last("LIMIT 1");
        return this.getOne(wrapper);
    }

}
